package com.fzj.example.socket.tcp.nonblock.aio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: AioServer
 * date: 2019/11/21 14:47
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class AioServer {
    private static Charset charset = Charset.forName("US-ASCII");
    private static CharsetEncoder encoder = charset.newEncoder();

    public static void main(String[] args) throws IOException, InterruptedException {
        //通道分组，也可以不分组
        AsynchronousChannelGroup group= AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(4));
        //线程池处理
        AsynchronousServerSocketChannel assc=AsynchronousServerSocketChannel.open(group);
        //绑定端口
        assc.bind(new InetSocketAddress(InetAddress.getByName("192.168.0.23"),9932));
        //
        assc.accept(null, new CompletionHandler< AsynchronousSocketChannel, Object >() {

            @Override
            public void completed(AsynchronousSocketChannel result, Object attachment) {
                assc.accept(null,this);//接收下一个连接
                try {
                    String now=new Date().toString();
                    ByteBuffer buffer = encoder.encode(CharBuffer.wrap(now + "\r\n"));
                    Future<Integer> future=result.write(buffer);
                    future.get();
                    System.out.println("sent to client: " + now);
                    result.close();
                } catch (CharacterCodingException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    }
}
